import * as signalR from "@aspnet/signalr";
import config from "@/config";
import tool from "@/utils/tool";
export default {
	SR: {},
	//初始化连接
	initSR: function () {
		let that = this;

		let userToken = tool.cookie.get("TOKEN");
		if (!userToken) return;
		// 1.获取系统中定义的baseURL
		let url = config.API_URL.replace(/http:/g, "");
		// 2.初始化连接
		that.SR = new signalR.HubConnectionBuilder()
			.withUrl(url + "/signalr", {
				headers: { Authorization: userToken },
				accessTokenFactory: () => userToken,
			})
			// .withAutomaticReconnect([0, 3000, 5000, 10000, 15000, 30000]) // 自动重连 该方法无效
			.configureLogging(signalR.LogLevel.Information)
			.build();
		// 3.携带参数
		that.SR.qs = {
			enc_auth_token: userToken,
		};
		// 4.启动连接的方法
		async function start() {
			try {
				await that.SR.start();
				console.log("signaR连接成功");
			} catch (err) {
				console.log("err", err);
				setTimeout(start, 5000);
			}
		}
		// 5.关闭之后重连
		that.SR.onclose(async () => {
			await start();
		});
		// 6.启动连接
		start();
		return true;
	},
	// 停止连接（这个方法好像没啥用，先放着吧）
	stopSR: function () {
		let that = this;
		async function stop() {
			try {
				await that.SR.stop();
				console.log("signaR退出成功");
			} catch (err) {
				console.log(err);
			}
		}
		stop();
	},
	offSR: function (eventName) {
		let that = this;
		if (that.SR) {
			that.SR.off(eventName);
		}
	},
};
